<template>
  <div id="supervision">
    <el-row>
      <el-col :xs="24" :sm="24" :lg="24" class="primary">监管项目配置</el-col>
    </el-row>
    <div class="filter">
      <div class="search">
        <label for="search">模糊搜索:</label>
        <el-input id="search" clearable v-model="filterItem.search" placeholder="请输入项目名/部门/PM"></el-input>
      </div>
      
      <div class="level marL">
        <label for="search">等级匹配:</label>
        <el-select v-model="filterItem.level" placeholder="请选择等级">
          <el-option
            v-for="item in levelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>

      <div class="supervised marL">
        <label for="search">是否监管匹配:</label>
        <el-select v-model="filterItem.isSupervised" placeholder="请选择是否监管">
          <el-option
            v-for="item in supervisedOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="saveButton">
        <el-button v-show="isEdit" @click="saveResult" round type="primary">保存提交</el-button>
        <el-button v-show="!isEdit" @click="edit" round type="success">编辑</el-button>
      </div>
    </div>

    <div class="bgColor" style="padding: 20px">
      <el-table
        :data="nowTable"
        border
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6'}"                      
        style="width: 100%">
        <el-table-column
          prop="project_name"
          label="项目名"
          align="center"
          >
        </el-table-column>
        <el-table-column
          prop="dept_name"
          label="部门"
          align="center"
          >
        </el-table-column>
        <el-table-column
          label="项目等级"
          align="center"
          >
          <template slot-scope="scope">
            <div v-if="isEdit">
              <el-select @change="changeLevel(scope.row, $event)" v-model="scope.row.project_level" placeholder="请选择">
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div v-else>{{ scope.row.project_level }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="product_manager"
          label="PM"
          align="center">
        </el-table-column>
        <el-table-column
          prop="project_status"
          label="状态"
          align="center">
        </el-table-column>

        <el-table-column
          prop="is_supervised"
          label="是否监管"
          align="center">
          <template slot-scope="scope">
            <div v-if="isEdit">
              <el-select v-model="scope.row.is_supervised" placeholder="请选择">
                <el-option
                  v-for="item in openOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div v-else>
              <span v-if="scope.row.is_supervised">是</span>
              <span v-else>否</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="owner(责任人)"
          align="center">
          <template slot-scope="scope">
            <div v-if="isEdit">
              <el-input 
                v-model="scope.row.owner" 
                autocomplete="off"
                placeholder="请指定责任人">
              </el-input>
            </div>
            <div v-else>{{ scope.row.owner }}</div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="marT"
        v-show="total > 10"
        :page-size="size"
        background                              
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="current"                               
        layout="prev, pager, next"
        style="text-align: center"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import http from '@/views/sys/axios'
  import { mapState } from 'vuex'

  export default {
    name: 'supervision',
    data() {
      return {
        tableData: [],
        current: 1,
        size: 10,
        total: 0,
        filterItem: {
          search: '',
          level: '',
          isSupervised: ''
        },
        timer: null,
        loading: false,
        error: false,
        isEdit: false,
        level: '',
        levelOptions: [
          {
            value: 'A类',
            label: 'A类'
          },
          {
            value: 'B类',
            label: 'B类'
          },
          {
            value: 'C类',
            label: 'C类'
          },
          {
            value: 'D类',
            label: 'D类'
          }
        ],        
        isOpen: '',
        openOptions: [
          {
            value: true,
            label: '是'
          },
          {
            value: false,
            label: '否'
          }
        ],
        supervisedOptions: [
          {
            value: '是',
            label: '是'
          },
          {
            value: '否',
            label: '否'
          }
        ]
      }
    },
    computed: {
      nowTable() {
        if(this.tableData.length) {
          return this.tableData.slice((this.current-1)*this.size, this.current*this.size)
        } else {
          return []
        }
      },
      ...mapState({
        dataChoose: state => state.dataChoose
      })
    },
    methods: {
      currentChange(val) {
        this.current = val
      },
      sizeChange(val) {
        this.size = val
      },
      changeLevel(row, val) {
        if(val == 'A类' || val == 'B类') {
          this.$set(row, 'is_supervised', true)
        }       
      },
      // debounce(func, delay) { 防抖函数
      //   return function(...args) {
      //     if(this.timer) {
      //       clearTimeout(this.timer)
      //     }
      //     this.timer = setTimeout(() => {
      //       func.apply(this, args)
      //     }, delay)
      //   }
      // },
      toSearch() {
        let params = `groupId=${this.dataChoose.selectId}&name=${this.filterItem.search}&level=${this.filterItem.level}&is_supervised=${this.filterItem.isSupervised}`
        return http.get(`/api/base/supervise/project?${params}`)
      },
      async searchResult() {
        try {
          this.loading = true
          const { code, data } = await this.toSearch()
          if(code === 200) {
            this.loading = false
            this.tableData = data
            this.total = this.tableData.length
            this.current = 1
          }
        } catch(err) {
          console.log(err)
          this.$message({
            message: '匹配错误,请重新匹配!',
            type: 'error'
          })
        }
      },
      save() {
        let data = this.nowTable
        const res = http.post(`/api/base/supervise/project?groupId=${this.dataChoose.selectId}`, data)        
        return res
      },
      async saveResult() {
        const list = this.nowTable.filter(item => item.project_level == 'A类' || item.project_level == 'B类')
        if(list.length) {
          if(!list[0].owner) {
            this.$message({
              message: 'AB类项目监管，请先指定owner(责任人)',
              type: 'error'
            })
            return
          }  
        }
           
        const resq = await this.save()
        if(resq.code === 200) {
          if(resq.msg === 'success') {
            this.$message({
              message: '保存成功!',
              type: 'success'
            })
            this.getTable()
          }
        } else {
          this.$message({
            message: resq.msg,
            type: 'error'
          })
        }
        
      },
      edit() {
        this.isEdit = true
      },
      init() {
        this.loading = true
        let res = http.get(`/api/base/supervise/project?groupId=${this.dataChoose.selectId}`)       
        return res
      },
      async getTable() {
        const resp = await this.init()
        this.loading = false
        if(resp.code === 200) {
          if(resp.data.length) {
            this.tableData = resp.data
            this.total = resp.data.length
          }
        }
      }
    },
    watch: {
      'dataChoose.selectId': {
        handler() {
          this.getTable()
        }
      },
      filterItem: {
        // 防抖 延时请求   
        handler: function(newVal) {
          clearTimeout(this.timer)
          this.timer = setTimeout(() => {
            if(newVal || newVal === '') {
              this.searchResult()
            }
          }, 1000)
        },
        deep:true           
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../assets/common/common.scss';
  /deep/ .el-table th.gutter{
    display: table-cell!important;
  }
  /deep/ .disabled{
    background: #F5F7FA;
  }
  .border{
    box-sizing: content-box;
    height: 0;
    overflow: visible;
    margin-top: 1rem;
    margin-bottom: 1rem;
    border: 0;
    border-top: 1px solid rgba(0,0,0,.1);
  }
  .filter{
    display: flex;
    margin-bottom: 20px;
    margin-top: 10px;
    .saveButton, .search{
      margin: auto 0;
    }
    .search{
      display: flex;
      label, #search{
        margin: auto 0;
      }
      label{
        width: 110px;
      }
    }
    .marL{
      margin-left: 20px;
    }
    .saveButton{
      margin-left: 50px;
    }
  }
  .primary{
    color: #409EFF;
    font-size: 30px;
    margin-top: 20px;
    margin-bottom: 10px;
    font-weight: 400;      
  }
  .bgColor{
    background: #fff;
  }
  .pad{
      padding: 0 20px;
      padding-top: 20px;
  }
  .marT{
      margin-top: 20px;
  }
</style>